import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type {
  Novel,
  Chapter,
  Comment,
  RecommendationItem,
  NovelCategory,
  SearchFilters,
} from "@/types";
import {
  getNovelsByCategory,
  getNovelById,
  getChaptersByNovelId,
  getChapterById,
  getCommentsByNovelId,
  getRecommendations,
  searchNovels,
  getPopularNovels,
  getLatestNovels,
} from "@/api/novels";

export const useNovelStore = defineStore("novel", () => {
  // 状态
  const novels = ref<Novel[]>([]);
  const currentNovel = ref<Novel | null>(null);
  const currentChapter = ref<Chapter | null>(null);
  const chapters = ref<Chapter[]>([]);
  const comments = ref<Comment[]>([]);
  const recommendations = ref<RecommendationItem[]>([]);
  const popularNovels = ref<Novel[]>([]);
  const latestNovels = ref<Novel[]>([]);
  const searchResults = ref<Novel[]>([]);
  const searchKeyword = ref("");
  const searchFilters = ref<SearchFilters>({});
  const loading = ref(false);

  // 计算属性
  const hasNovels = computed(() => novels.value.length > 0);
  const hasRecommendations = computed(() => recommendations.value.length > 0);
  const currentChapterIndex = computed(() => {
    if (!currentChapter.value) return -1;
    return chapters.value.findIndex((ch) => ch.id === currentChapter.value?.id);
  });
  const hasNextChapter = computed(() => {
    return currentChapterIndex.value >= 0 && currentChapterIndex.value < chapters.value.length - 1;
  });
  const hasPrevChapter = computed(() => {
    return currentChapterIndex.value > 0;
  });

  /**
   * 获取小说列表
   */
  const fetchNovels = async (category?: NovelCategory) => {
    try {
      loading.value = true;
      const data = await getNovelsByCategory(category);
      novels.value = data;
    } catch (error) {
      console.error("Failed to fetch novels:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取小说详情
   */
  const fetchNovelDetail = async (id: string) => {
    try {
      loading.value = true;
      const novel = await getNovelById(id);
      if (novel) {
        currentNovel.value = novel;
        // 同时加载章节列表和评论
        await Promise.all([fetchChapters(id), fetchComments(id)]);
      }
    } catch (error) {
      console.error("Failed to fetch novel detail:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取章节列表
   */
  const fetchChapters = async (novelId: string) => {
    try {
      const data = await getChaptersByNovelId(novelId);
      chapters.value = data;
    } catch (error) {
      console.error("Failed to fetch chapters:", error);
    }
  };

  /**
   * 获取章节内容
   */
  const fetchChapter = async (chapterId: string) => {
    try {
      loading.value = true;
      const chapter = await getChapterById(chapterId);
      if (chapter) {
        currentChapter.value = chapter;
      }
    } catch (error) {
      console.error("Failed to fetch chapter:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取下一章
   */
  const fetchNextChapter = async () => {
    const nextIndex = currentChapterIndex.value + 1;
    if (nextIndex < chapters.value.length) {
      const nextChapter = chapters.value[nextIndex];
      await fetchChapter(nextChapter.id);
    }
  };

  /**
   * 获取上一章
   */
  const fetchPrevChapter = async () => {
    const prevIndex = currentChapterIndex.value - 1;
    if (prevIndex >= 0) {
      const prevChapter = chapters.value[prevIndex];
      await fetchChapter(prevChapter.id);
    }
  };

  /**
   * 获取评论
   */
  const fetchComments = async (novelId: string) => {
    try {
      // TODO: 暂时禁用评论API调用，因为后端还未实现
      // const data = await getCommentsByNovelId(novelId);
      // comments.value = data;

      // 临时返回空数组，避免API调用失败
      comments.value = [];
      console.log("评论功能暂时禁用，novelId:", novelId);
    } catch (error) {
      console.error("Failed to fetch comments:", error);
      comments.value = [];
    }
  };

  /**
   * 获取推荐小说
   */
  const fetchRecommendations = async (userId?: string) => {
    try {
      const data = await getRecommendations(userId);
      recommendations.value = data;
    } catch (error) {
      console.error("Failed to fetch recommendations:", error);
    }
  };

  /**
   * 获取热门小说
   */
  const fetchPopularNovels = async () => {
    try {
      const data = await getPopularNovels();
      popularNovels.value = data;
    } catch (error) {
      console.error("Failed to fetch popular novels:", error);
    }
  };

  /**
   * 获取最新更新小说
   */
  const fetchLatestNovels = async () => {
    try {
      const data = await getLatestNovels();
      latestNovels.value = data;
    } catch (error) {
      console.error("Failed to fetch latest novels:", error);
    }
  };

  /**
   * 搜索小说
   */
  const searchNovel = async (keyword: string, filters?: SearchFilters) => {
    try {
      loading.value = true;
      searchKeyword.value = keyword;
      searchFilters.value = filters || {};

      const data = await searchNovels(keyword);
      searchResults.value = data;
    } catch (error) {
      console.error("Failed to search novels:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 清空搜索结果
   */
  const clearSearch = () => {
    searchResults.value = [];
    searchKeyword.value = "";
    searchFilters.value = {};
  };

  /**
   * 按分类获取小说
   */
  const getNovelsByCategoryFilter = (category: NovelCategory) => {
    return novels.value.filter((novel) => novel.category === category);
  };

  /**
   * 获取小说标签
   */
  const getAllTags = computed(() => {
    const tags = new Set<string>();
    novels.value.forEach((novel) => {
      novel.tags.forEach((tag) => tags.add(tag));
    });
    return Array.from(tags);
  });

  /**
   * 初始化首页数据
   */
  const initHomeData = async () => {
    try {
      loading.value = true;
      await Promise.all([
        fetchNovels(),
        fetchPopularNovels(),
        fetchLatestNovels(),
        fetchRecommendations(),
      ]);
    } catch (error) {
      console.error("Failed to init home data:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 重置当前小说和章节
   */
  const resetCurrent = () => {
    currentNovel.value = null;
    currentChapter.value = null;
    chapters.value = [];
    comments.value = [];
  };

  /**
   * 增加浏览量（模拟）
   */
  const increaseViewCount = (novelId: string) => {
    const novel = novels.value.find((n) => n.id === novelId);
    if (novel) {
      novel.viewCount += 1;
    }
    if (currentNovel.value?.id === novelId) {
      currentNovel.value.viewCount += 1;
    }
  };

  /**
   * 添加评论（模拟）
   */
  const addComment = (comment: Omit<Comment, "id" | "createdAt">) => {
    const newComment: Comment = {
      ...comment,
      id: "comment_" + Date.now(),
      createdAt: new Date().toISOString(),
    };
    comments.value.unshift(newComment);
  };

  /**
   * 点赞评论（模拟）
   */
  const likeComment = (commentId: string) => {
    const comment = comments.value.find((c) => c.id === commentId);
    if (comment) {
      comment.likeCount += 1;
    }
  };

  /**
   * 加载更多评论（模拟）
   */
  const loadMoreComments = (novelId: string) => {
    console.log("Loading more comments for novel:", novelId);
    // 模拟功能，实际应该从API加载更多评论
  };

  return {
    // 状态
    novels,
    currentNovel,
    currentChapter,
    chapters,
    comments,
    recommendations,
    popularNovels,
    latestNovels,
    searchResults,
    searchKeyword,
    searchFilters,
    loading,

    // 计算属性
    hasNovels,
    hasRecommendations,
    currentChapterIndex,
    hasNextChapter,
    hasPrevChapter,
    getAllTags,

    // 方法
    fetchNovels,
    fetchNovelDetail,
    fetchChapters,
    fetchChapter,
    fetchNextChapter,
    fetchPrevChapter,
    fetchComments,
    fetchRecommendations,
    fetchPopularNovels,
    fetchLatestNovels,
    searchNovel,
    clearSearch,
    getNovelsByCategoryFilter,
    initHomeData,
    resetCurrent,
    increaseViewCount,
    addComment,
    likeComment,
    loadMoreComments,
  };
});
